#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
#include "seqiot.h"
#include "sqlite.h"
#include "sysinfo.h"

sys_info_t *sys_info_new() {
    return z_calloc(1, sizeof(sys_info_t));
}

void sys_info_free(sys_info_t *ptr) {
    z_free(ptr);
}

void read_row_sys_info(sqlite3_stmt *stmt, sys_info_t *rs) {
    int idx = 0;

    read_row_str(stmt, idx++, rs->id, sizeof(rs->id));
    replace_metric(rs->id, sizeof(rs->id));
    read_row_str(stmt, idx++, rs->name, sizeof(rs->name));
    read_row_str(stmt, idx++, rs->cmd, sizeof(rs->cmd));
}

int read_stmt_sys_infos(sqlite3 *db, vector_t *infos) {
    int rc;
    sqlite3_stmt *stmt = NULL;
    char sql[1024];

    sprintf(sql, "SELECT id,name,cmd_line FROM sys_info WHERE %s", SQL_DISABLE);
    rc = sqlite3_prepare(db, sql, -1, &stmt, NULL);
    if (SQLITE_OK != rc) {
        sqlite_check(db);
        goto err;
    }

    while (SQLITE_ROW == sqlite3_step(stmt)) {
        sys_info_t *info = sys_info_new();
        read_row_sys_info(stmt, info);
        vector_add(infos, info);
    }

    err:
    sqlite3_finalize(stmt);
    return rc;
}

int sys_info_exec_string(const char *cmd, char *buf, int size) {
    int rc = -1;
    if (NULL == cmd) return -1;

    FILE *fp = popen(cmd, "r");
    if (NULL == fp) return -1;

    if (NULL != fgets(buf, size, fp)) {
        rc = 0;
    }

    pclose(fp);

    return rc;
}

int sys_info_exec_double(const char *cmd, double *value) {
    if (NULL == value) return -1;

    char buf[256];
    int rc = sys_info_exec_string(cmd, buf, sizeof(buf));
    if (0 == rc) {
        *value = strtod(buf, NULL);
    }
    return rc;
}